﻿using System.Reflection;
using Volo.Abp;
using Volo.Abp.DependencyInjection;
using XCWechat.ApiConsts;
using XCWechat.Entities.Clients;
using XCWechat.Helpers;
using XCWechat.Repositories;
using XCWechat.XCAPIs;

namespace XCWechat.Services.BaseDatas
{
    [Dependency(ServiceLifetime.Transient)]
    public class CustomerApiService : ICustomerApiService, IRemoteService
    {
        public IClientInfoRepository ClientRepository { get; set; }

        public async Task<string> GetCustomerListAsync()
        {
            ClientInfo clientInfo = await ClientRepository.GetClientInfoAsync();
            var apiClient = new XCAPIClient(clientInfo.ClientId, clientInfo.ClientSecret);
            Assembly assembly = Assembly.Load("XCWechat");
            Type? type = assembly.GetType("XCWechat.ApiConsts.PathConst");
            FieldInfo? fieldInfo = type.GetField("Customer");
            string path = fieldInfo.GetValue("Customer").ToString();
            var apiRequest = new XCAPIRequest
            {
                Method = HttpMethod.Get,
                Path = path
            };
            apiRequest.Params.Add("app_key", clientInfo.AppKey);
            apiRequest.Params.Add("app_signature", SHAHelper.HmacSHA256(clientInfo.AppSecret, clientInfo.AppKey));
            HttpResponseMessage responseMessage = await apiClient.Execute(apiRequest, clientInfo.AppToken);
            string result = responseMessage.Content.ReadAsStringAsync().Result;
            return result;
        }
    }
}
